package config_table

import (
	"base"
	"config/internal/global"
	"config/item"
	"encoding/json"
	"fmt"
)

type globalTable struct {
	// item id
	GoldCoinItemId base.AssetItemId
	DiamondItemId  base.AssetItemId

	// reward
	InitReward base.AssetItems
}

type globalConfig []*config_item.Global

var (
	Global *globalTable
)

func init() {
	register(Global.parse, new(globalConfig), "global/global_config.json")
}

func (table *globalTable) parse(records interface{}) (err error) {
	type Item = config_item.Global
	items := make(map[string]interface{})
	handlers := global.KeyParsers

	for _, item := range *records.(*globalConfig) {
		key := item.Key
		if _, exists := items[key]; exists {
			err = fmt.Errorf("key: %s is exist", key)
			return
		}

		if handler, exists := handlers[key]; exists {
			var value interface{}
			value, err = handler(item.Value)
			if err != nil {
				err = fmt.Errorf("convert global key: %s failed, %s", key, err)
				return
			}

			items[key] = value
		}
	}

	var data []byte
	if data, err = json.Marshal(items); err != nil {
		return
	}

	temp := new(globalTable)
	if err = json.Unmarshal(data, temp); err != nil {
		return
	}

	Global = temp

	return
}
